import { Component, useState, useEffect } from 'react'
import { View, Input, Text, Image, Navigator } from '@tarojs/components'
import Taro, {usePullDownRefresh} from '@tarojs/taro'
import { AtPagination } from 'taro-ui'

import './index.scss'

type ListItemProps  = {
  create_at: string;
  avatar: string;
  share: number;
  star: number;
  tabs: string;
  title: string;
  top: number;
  user_name: string;
  user_id: string;
  _id: string;
}
type ResultProps = {
  errCode: string;
  errMsg: string;
  data: null | ListItemProps[];
  total: number;
}

interface ResProps extends Taro.cloud.CallFunctionResult {
  result: ResultProps;
  [key: string]: any;
}

const Index = () => {
  const [current, setCurrent] = useState(1)
  const [pageTotal, setPageTotal] = useState(1)
  const [tieziList, setTieziList] = useState<null|ListItemProps[]>(null)

  useEffect(() => {
    getTieziList(current)
  }, [])

  // 下拉刷新
  usePullDownRefresh(() => {
    setCurrent(1);
    getTieziList(1);
  })

  // 列表请求
  function getTieziList(current: number) {
    Taro.cloud.callFunction({
      name: 'tiezi',
      data: {
        type: 'getTieziList',
        current,
        pageSize: 2
      }
    })
    .then(function(res: ResProps) {
      console.log('云函数返回帖子列表：', res)

      if(res.result.errCode === '200') {
        setTieziList(res.result.data)
        setPageTotal(res.result.total)
      }
    })
    .catch(err => {
      console.log('获取帖子失败：', err)
      Taro.showToast({
        title: '获取数据失败，稍后重试'
      })
    })
  }

  const searchHandler = () => {
    Taro.navigateTo({
      url: '../tieSearch/index'
    })
  }

  // 页码改变
  const pageChange = (type) => {
    console.log('页码改变:', type.current)
    setCurrent(type.current)
    getTieziList(type.current)
  }

  const ListDom = function() {
    if(tieziList === null) {
      return '暂无数据'
    } else {
      return tieziList.map(item => {
        return (
          <Navigator url={'../tieDetail/index?id=' + item._id} className='tiezi-item' key={item._id}>
            <View className='tiezi-user'>
              <Image mode='aspectFill' src={item.avatar} className='tiezi-avatar'></Image>
              <Text className='tiezi-username'>{item.user_name}</Text>
            </View>
            <View className='tiezi-body'>
              <View className='tiezi-title'>{item.title}</View>
              {/* <View className='tiezi-content'>{item.conetnt}</View> */}
            </View>
            <View className='tiezi-footer'>
              <View className='tiezi-share'>
                <Text className='iconfont icon-fenxiang'></Text>
                <Text className="tiezi-footer-num">{item.share}</Text>
              </View>
              <View className='tiezi-comment'>
                <Text className='iconfont icon-pinglun'></Text>
                <Text className="tiezi-footer-num">1</Text>
              </View>
              <View className='tiezi-star'>
                <Text className='iconfont icon-31dianzan'></Text>
                <Text className="tiezi-footer-num">{item.star}</Text>
              </View>
            </View>
          </Navigator>
        )
      })
    }
  }

  const paginDom = (
    <AtPagination 
      total={pageTotal} 
      pageSize={2}
      current={current}
      icon={true}
      onPageChange={pageChange}
    >
    </AtPagination>
  )
 
  return (
    <View className='index'>
      <View className='index-search'>
        <Input onClick={searchHandler} className='search' placeholder='输入关键词搜索' />
        <Text className='iconfont icon-sousuo index-search-icon' />
      </View>

      <View className='tiezi-list'>
        {ListDom()}
      </View>
      {paginDom}

      {/* 添加帖子按钮 */}
      <Navigator className="add-btn" url="../addTie/index">
        <Text className="iconfont icon-tianjia1"></Text>
      </Navigator>
    </View>
  )
}

export default Index

